//
//  LSFirstListenController.m
//  听说弱点强化训练
//
//  Created by 盛超 on 2018/8/22.
//  Copyright © 2018年 盛超. All rights reserved.
//

#import "LSResFirstController.h"
#import "LSBackButton.h"
#import "LSFirstCell.h"
#import "LSResListManager.h"
#import "LSResPackageController.h"
#import "ZBFtpTools.h"
#import "KZAlertView.h"
#import "LSFtpManager.h"

@interface LSResFirstController ()<UITableViewDataSource,UITableViewDelegate>

@property (nonatomic,strong) LSModelLSResList *model;

@end

@implementation LSResFirstController

- (void)setTypeID:(NSString *)TypeID {
    _TypeID = TypeID;
    
    NSLog(@"%ld===%ld====%f",LS_System.listenScore,LS_System.readScore,LS_System.lowSpeed);
  //  [self loadData];
}

- (void)loadData {
    LSResListManager *manager = [[LSResListManager alloc] init];
    NSDictionary *dict = @{@"StuID":DR_UserInfo.UserID,
                           @"StageNo":KGetUserDefaults(@"TestLayer"),
                           @"SchoolID":KGetUserDefaults(@"SchoolID"),
                           @"TypeID":_TypeID,
                           @"UpdateTime":_UpdateTime?_UpdateTime:@""
                           };

    [MBProgressHUD showLoadind:@"正在加载关卡，请稍候..."];
    manager.requestParam = @{@"DictString":[NSObject objectToJson:dict]};
    [manager requestWithCompltionSuccess:^(LSModelLSResList *model) {
        
        self.model = model;
        
        //初始化ftp配置
        [ZBFtpTools ZBFtp_setupInitWithHost:model.FtpServerAddress
                                       user:model.sUserName
                                        psw:model.sUserPwd];

        dispatch_async(dispatch_get_main_queue(), ^{
            [self.tableView reloadData];
            [MBProgressHUD hideHud];
        });
        
    } failuer:^(NSString *error) {
        
        dispatch_async(dispatch_get_main_queue(), ^{
            [MBProgressHUD hideHud];
        });
    }];
}

- (void)viewDidLoad {
    [super viewDidLoad];

    UIImageView *imageView = [[UIImageView alloc] init];
    imageView.image = [UIImage imageNamed:@"LS-大背景"];
    [self.view addSubview:imageView];
    [imageView mas_makeConstraints:^(MASConstraintMaker *make) {
        make.left.right.top.bottom.equalTo(self.view);
    }];
    
    [self setUpBackItem];

    self.tableView = [[UITableView alloc] init];
    self.tableView.scrollEnabled = NO;
    self.tableView.backgroundColor = [UIColor clearColor];
    self.tableView.rowHeight = 160*ScalesH;//(kHeight-kNavgationBar-100*ScalesH)/3;
    self.tableView.separatorStyle = UITableViewCellSeparatorStyleNone;
    self.tableView.delegate = self;
    self.tableView.dataSource = self;
    [self.tableView registerClass:[LSFirstCell class] forCellReuseIdentifier:@"LSFirstCell"];
    [self.view addSubview:self.tableView];
    [self.tableView mas_makeConstraints:^(MASConstraintMaker *make) {
        make.left.right.equalTo(self.view);
        if (@available(iOS 11.0, *)) {
            make.bottom.equalTo(self.view.mas_safeAreaLayoutGuideBottom);
            make.top.equalTo(self.view.mas_safeAreaLayoutGuideTop);
        } else {
            make.top.equalTo(self.view).offset(kNavgationBar);
            make.bottom.equalTo(self.view);
        }
    }];
    self.tableView.tableHeaderView = [self createTableViewHeader];
    if (@available(iOS 11.0, *)) {
        self.tableView.contentInsetAdjustmentBehavior = UIScrollViewContentInsetAdjustmentNever;
    }else {
        self.automaticallyAdjustsScrollViewInsets = NO;
    }
}

- (void)setUpBackItem {
    NSString *text = @"听力能力强化训练";
    NSString *imageName = @"LS-head_set";
    if ([_TypeID isEqualToString:@"Spn"]||[_TypeID isEqualToString:@"Sp"]) {
        text = @"朗读能力强化训练";
        imageName = @"LS-朗读能力强化训练图标";
    }
    
    UIControl *backView = [[UIControl alloc] initWithFrame:CGRectMake(0, 0, 200, 40)];
    [backView addTarget:self action:@selector(backAction:) forControlEvents:UIControlEventTouchUpInside];
    self.navigationItem.leftBarButtonItem = [[UIBarButtonItem alloc] initWithCustomView:backView];
    
    UIImageView *backImageView = [[UIImageView alloc] initWithFrame:CGRectMake(0, 0, 0, 0)];
    backImageView.image = [UIImage imageNamed:@"kz-关闭"];
    [backView addSubview:backImageView];
    [backImageView sizeToFit];
    backImageView.centerY = backView.height / 2;
    
    UIImageView *iconView = [[UIImageView alloc] initWithFrame:CGRectMake(backImageView.right+5, 10, 20, 20)];
    iconView.image = [UIImage imageNamed:imageName];
    [backView addSubview:iconView];
    [iconView sizeToFit];
    iconView.centerY = backView.height / 2;
    
    UILabel *label = [[UILabel alloc] initWithFrame:CGRectMake(iconView.right+5, 0, [text getSizeOfBlodString:20].width, 40)];
    label.adjustsFontSizeToFitWidth = true;
    label.numberOfLines = 1;
    label.text = text;
    label.font = B_FONT(20);
    label.textAlignment = NSTextAlignmentCenter;
    label.textColor = [UIColor whiteColor];
    [backView addSubview:label];
    
    backView.width = label.right;
}

- (UIView*)createTableViewHeader {
    
    UIView *header = [[UIView alloc] initWithFrame:CGRectMake(0, 0, kWidth, 100*ScalesH)];
    UILabel *titleLabel = [[UILabel alloc] init];//WithFrame:CGRectMake(10, 0, kWidth-20,100*ScalesH)];
    NSString *text = @"采用过关式认知训练方式,\n设置3道听力关卡,快速提升听力能力!";
    if ([_TypeID isEqualToString:@"Spn"]||[_TypeID isEqualToString:@"Sp"]) {
        text = @"采用过关式认知训练方式,\n设置3道朗读关卡,快速提升朗读能力!";
    }
    
    
    NSRange range = [text rangeOfString:@"3"];
    titleLabel.textColor = [UIColor whiteColor];
    titleLabel.font = [UIFont systemFontOfSize:15.0f*ScalesW];
    titleLabel.textAlignment = NSTextAlignmentCenter;
    titleLabel.numberOfLines = 0;
    NSMutableAttributedString *attr = [[NSMutableAttributedString alloc] initWithString:text];
    [attr addAttributes:@{NSFontAttributeName:[UIFont systemFontOfSize:17.0f*ScalesW],NSForegroundColorAttributeName:[UIColor yellowColor]} range:range];
    titleLabel.attributedText = attr;
 
    [header addSubview:titleLabel];
    
    [titleLabel mas_makeConstraints:^(MASConstraintMaker *make) {
        make.center.equalTo(header);
        make.size.mas_equalTo(CGSizeMake(250*ScalesW, 40*ScalesW));
    }];
    
    UIButton *btn = [[UIButton alloc] init];
    [btn setImage:[UIImage imageNamed:@"LS-说明2"] forState:UIControlStateNormal];
    [header addSubview:btn];
    [btn mas_makeConstraints:^(MASConstraintMaker *make) {
        make.left.equalTo(titleLabel.mas_right).offset(2);
        make.centerY.equalTo(titleLabel.mas_centerY).offset(10*ScalesW);
        make.size.mas_equalTo(CGSizeMake(13*ScalesW, 13*ScalesW));
    }];
    [btn addTarget:self action:@selector(showAlertView) forControlEvents:UIControlEventTouchUpInside];
    
    return header;
}

- (void)showAlertView {
    KZAlertView *alert = [KZAlertView new];
    NSString *text = @"您需要作答20道题完成第一轮训练,\n作答全部正确才能通关哟~\n\n论学习，小鸽是很严格的";
    NSMutableAttributedString *attrStr = [[NSMutableAttributedString alloc] initWithString:text];
    [alert showWithTitle:@"温馨提示" subtitle:attrStr submitTypes:@[@0] submitButtonsConfig:^(NSArray<UIButton *> *buttons) {
        [buttons.firstObject setTitle:@"继续训练" forState:UIControlStateNormal];
        
    } click:^(NSInteger index) {
        
        
    } destroyAtClickIndex:@[@0]];
}

- (void)viewWillAppear:(BOOL)animated {
    [super viewWillAppear:animated];
    [self setNaviAttributeWithTranslucent:YES stateBarLightContent:YES];
    [[NSNotificationCenter defaultCenter] postNotificationName:@"TimeRelease" object:nil];
    
    [self loadData];
}

- (void)backAction:(UIButton*)sender {
    [self.navigationController dismissViewControllerAnimated:YES completion:nil];
}

- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

#pragma mark - tableViewDelegate
- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath
{
    
}

//- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath {
//    return ScalesH * 160;
//}

#pragma mark - tableViewDatasource
- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section {
    return 3;
}

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
    
    LSFirstCell *cell = [tableView dequeueReusableCellWithIdentifier:@"LSFirstCell"];
    WeakObj(self);
    cell.pushBlock = ^{
        LSResPackageController *vc = [[LSResPackageController alloc] init];
        vc.model = selfWeak.model;
        [selfWeak push:vc];
    };
  
    if([_model.PackageID isEqualToString:@""]) {
        _model.PackageStage = 100;//ID为空时，三关全部通关
    }
    
    cell.dict = @{@"IndexPathRow":@(indexPath.row),
                  @"Stage":@(_model.PackageStage),
                  @"TypeID":_TypeID
                  };
    return cell;
}

- (void)dealloc {
    NSLog(@"first销毁");
}

/*
#pragma mark - Navigation

// In a storyboard-based application, you will often want to do a little preparation before navigation
- (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender {
    // Get the new view controller using [segue destinationViewController].
    // Pass the selected object to the new view controller.
}
*/

@end
